package daliytool;

import daliytool.http.server.HttpServer;
import daliytool.script.FileFunctionScript;
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker.State;
import javafx.event.ActionEvent;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Hyperlink;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.web.PopupFeatures;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import netscape.javascript.JSObject;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author shuaidongdong
 */
@SuppressWarnings("ALL")
public class WebViewMain extends Application {

    public static Stage stageNow;
    private  static final ExecutorService executorService = Executors.newSingleThreadExecutor();
    @Override
    public void start(Stage stage) {
        stageNow = stage;
        stage.setTitle("日常小工具");
        Scene scene = new Scene(new Browser(stage), 900, 600, Color.web("#666970"));
        stage.setScene(scene);
        scene.getStylesheets().add("daliytool/css/BrowserToolbar.css");
        stage.show();

        /*关闭netty 服务端*/
        stage.setOnCloseRequest(event -> {
            HttpServer.shutdown();
            executorService.shutdown();
        });

    }

    public static void main(String[] args) {
        //异步启动netty服务端
        executorService.execute(()->{
            HttpServer.run("127.0.0.1", 11209);
        });

        launch(args);
    }
}

class Browser extends Region {
    private final HBox toolBar;
    final private static String[] IMAGE_FILES = new String[]{
        "img/product.png",
        "img/blog.png",
        "img/help.png"
    };

    final private static String[] CAPTIONS = new String[]{
        "代码清单",
        "历史清单",
        "帮助"
    };

    final private static String[] URLS = new String[]{
            WebViewMain.class.getResource("index.html").toExternalForm(),
            WebViewMain.class.getResource("history.html").toExternalForm(),
            WebViewMain.class.getResource("format.html").toExternalForm()
    };

    private final WebView browser = new WebView();
    private final WebEngine webEngine = browser.getEngine();
    private final WebView smallView = new WebView();


    public Browser(final Stage stage) {
        //apply the styles
        getStyleClass().add("browser");

        Hyperlink[] hpls = new Hyperlink[CAPTIONS.length];
        for (int i = 0; i < CAPTIONS.length; i++) {
            // create hyperlinks
            Hyperlink hpl = hpls[i] = new Hyperlink(CAPTIONS[i]);
            Image[] images = new Image[IMAGE_FILES.length];
            Image image = images[i]
                    = new Image(getClass().getResourceAsStream(IMAGE_FILES[i]));
            hpl.setGraphic(new ImageView(image));
            final String url = URLS[i];

            // process event
            hpl.setOnAction((ActionEvent e) -> {
                loadPage(url);
            });

        }


        ComboBox comboBox = new ComboBox();
        comboBox.setPrefWidth(60);

        // create the toolbar
        toolBar = new HBox();
        toolBar.setAlignment(Pos.CENTER);
        toolBar.getStyleClass().add("browser-toolbar");
        toolBar.getChildren().addAll(hpls);
        toolBar.getChildren().add(createSpacer());

        smallView.setPrefSize(120, 80);

        //handle popup windows
        webEngine.setCreatePopupHandler(
                (PopupFeatures config) -> {
                    smallView.setFontScale(0.8);
                    if (!toolBar.getChildren().contains(smallView)) {
                        toolBar.getChildren().add(smallView);
                    }
                    return smallView.getEngine();
        });


        // process page loading
        webEngine.getLoadWorker().stateProperty().addListener(
            (ObservableValue<? extends State> ov, State oldState,
                State newState) -> {
                    if (newState == State.SUCCEEDED) {
                        JSObject win = (JSObject) webEngine.executeScript("window");
                        win.setMember("fileOpt",new FileFunctionScript());
                    }
        });

        // load the home page
        loadPage(URLS[1]);

        //add components
        getChildren().add(toolBar);
        getChildren().add(browser);
    }

    private void loadPage(String path){
        webEngine.load(path);
    }



    private Node createSpacer() {
        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);
        return spacer;
    }

    @Override
    protected void layoutChildren() {
        double w = getWidth();
        double h = getHeight();
        double tbHeight = toolBar.prefHeight(w);
        layoutInArea(browser,0,0,w,h-tbHeight,0,HPos.CENTER,VPos.CENTER);
        layoutInArea(toolBar,0,h-tbHeight,w,tbHeight,0,HPos.CENTER,VPos.CENTER);
    }

    @Override
    protected double computePrefWidth(double height) {
        return 900;
    }

    @Override
    protected double computePrefHeight(double width) {
        return 600;
    }
}
